package com.basics.common.utils.http;


import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;

/**
 * 获取https访问权限
 *
 * @author LVXY 2016年11月18日 上午11:51:15
 * @version V2.0
 *
 */
public abstract class SSLUtils {
	/**
	* 绕过验证
	*
	* @return
	* @throws NoSuchAlgorithmException
	* @throws KeyManagementException
	 * @throws NoSuchProviderException
	*/
	public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException, NoSuchProviderException {
	        SSLContext sc = SSLContext.getInstance("SSL", "SunJSSE");
	        // 实现一个X509TrustManager接口，用于绕过验证，不用修改里面的方法
	        X509TrustManager trustManager = new X509TrustManager() {
	            @Override
	            public void checkClientTrusted(
	                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
	                    String paramString) throws CertificateException {
	            }

	            @Override
	            public void checkServerTrusted(
	                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
	                    String paramString) throws CertificateException {
	            }

	            @Override
	            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
	                return null;
	            }
	        };

	        sc.init(null, new TrustManager[] { trustManager }, null);
	        return sc;
	    }

	public static void setSSL(){
		//采用绕过验证的方式处理https请求
        SSLContext sslcontext;
		try {
				sslcontext = createIgnoreVerifySSL();
			//设置协议http和https对应的处理socket链接工厂的对象
			Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
					.register("http", PlainConnectionSocketFactory.INSTANCE)
					.register("https", new SSLConnectionSocketFactory(sslcontext))
					.build();
			PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
			HttpClients.custom().setConnectionManager(connManager);
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchProviderException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
